<template>
  <div style="height: 100%;overflow: auto;margin-top: 20px;">
    <!-- <el-divider style="margin: 0 0 14px 0;"></el-divider> -->
    <el-form :inline="true"
             class="coverage-style-searchForm">
      <el-form-item>
        <div class="demo-input-suffix">
          <el-input prefix-icon="el-icon-search"
                    clearable
                    placeholder="请输入模板名称"
                    v-model="setNoticeTMPName">
          </el-input>
        </div>
      </el-form-item>
      <el-form-item>
        <button @click="searchTmpContent"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">查询</button>
      </el-form-item>
      <el-form-item class="fr">
        <button @click="createForm"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">新建通知模板</button>
      </el-form-item>
    </el-form>

    <el-row>
      <el-table class="table-td"
                ref="multipleTable"
                stripe
                border
                :header-cell-style="{background:'#F2F3F8'}"
                :data="tableData"
                @select="pinSelect"
                v-loading="loading"
                tooltip-effect="dark"
                style="width:100%"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection"
                         align="center"
                         min-width="10%"></el-table-column>
        <el-table-column label="模板名称"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">
            <span style="color: #2393f1">{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态"
                         min-width="15%"
                         align="center">
          <template slot-scope="scope">{{ scope.row.status == 1 ? '启用' : '停用'}}</template>
        </el-table-column>
        <el-table-column label="创建时间"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">{{ scope.row.updateTime }}</template>
        </el-table-column>
        <el-table-column label="创建人"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">{{ scope.row.updaterName }}</template>
        </el-table-column>
        <el-table-column label="模板类型"
                         align="center"
                         min-width="20%">
          <template slot-scope="scope">{{ scope.row.dictName }}</template>
        </el-table-column>
        <el-table-column label="操作"
                         align="center"
                         min-width="40%"
                         show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text"
                       size="mini"
                       class="run-and-stop"
                       @click="handleChange(scope.$index, scope.row)">
              <span v-if="scope.row.status !== 1">
                <img src="../../../assets/images/start.png"
                     alt />启用
              </span>
              <span v-else>
                <img src="../../../assets/images/stop.png"
                     alt />停用
              </span>
            </el-button>
            <el-button icon="el-icon-delete"
                       type="text"
                       size="mini"
                       class="btn"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button icon="el-icon-edit"
                       type="text"
                       size="mini"
                       class="btn"
                       @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="paging-foot page-foot-spacing"
            :gutter="20">
      <el-col :span="12">
        <span class="color-select">批量操作</span>
        <span class="select-number">（已选中{{selectAllIdLength}}条）</span>
        <button @click="deleteBatch"
                type="button"
                class="el-button el-button--primary el-button--medium h30Btn ">删除</button>
      </el-col>
      <el-col :span="12">
        <div>
          <el-pagination background
                         class="el-pagination-style"
                         v-show="totalDataLength > 0"
                         @size-change="handleSizeChange"
                         @current-change="handleCurrentChange"
                         :current-page="pageNumber"
                         :page-sizes="[10, 20, 50, 100]"
                         :page-size="pageSize"
                         layout="total, sizes, prev, pager, next, jumper"
                         :total="totalDataLength"></el-pagination>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  deleteListMsg,
  startClose,
  getListNotice,
} from '@/api/setNotice'
import common from '@/common/common.js'
export default {
  data () {
    return {
      lists: [],
      changeLists: [],
      origin: -1,
      pin: false,
      pageNumber: 1,
      pageSize: 10,
      tableData: [],
      selectAllId: [],
      selectAllIdLength: 0,
      setNoticeTMPName: '',
      totalDataLength: 0,
    }
  },
  mounted () {
    // 默认查询
    this.searchTmp()
    window.addEventListener('keydown', code => { // 这个是获取键盘按住事件
      // console.log(code) // 这个是你按住键盘打印出键盘信息，在浏览器中自行查看
      if (code.keyCode === 16 && code.shiftKey) { // 判断是否按住shift键，是就把pin赋值为true
        this.pin = true
      }
    })
    window.addEventListener('keyup', code => { // 这个是获取键盘松开事件
      if (code.keyCode === 16) { // 判断是否松开shift键，是就把pin赋值为false
        this.pin = false
        if (this.lists.length > 2) {
          this.selectAllId = this.lists
        } else {
          this.selectAllId = this.changeLists
        }
        this.selectAllIdLength = this.selectAllId.length
      }
    })
  },
  destroyed () {
    window.removeEventListener('keydown', code => {
      if (code.keyCode === 16 && code.shiftKey) {
        this.pin = true
      }
    }, false)
    window.removeEventListener('keyup', code => {
      if (code.keyCode === 16) {
        this.pin = false
      }
    }, false)
  },
  methods: {
    // 这里是select事件开始
    pinSelect (item, row) {
      const data = this.tableData // 获取所有数据
      const origin = this.origin // 起点数 从-1开始
      const endIdx = row.index // 终点数
      if (this.pin && item.includes(data[origin])) { // 判断按住
        // this.$refs.multipleTable.selectClear()
        const sum = Math.abs(origin - endIdx) + 1// 这里记录终点
        const min = Math.min(origin, endIdx)// 这里记录起点
        let i = 0

        while (i < sum) {
          const index = min + i
          this.$refs.multipleTable.toggleRowSelection(data[index], true) // 通过ref打点调用toggleRowSelection方法，第二个必须为true
          i++
        }
        this.lists = this.selectAllId
      } else {
        this.origin = row.index // 没按住记录起点或没选起点
        this.lists = []
      }
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
      this.pageNumber = 1
      this.searchTmp()
    },
    handleCurrentChange (pageNumber) {
      this.pageNumber = pageNumber
      this.searchTmpContent()
    },
    handleChange (index, row) {
      let status = row.status
      if (status === 0) {
        status = 1
      } else {
        status = 0
      }
      let params = {
        // userId: this.$store.state.userId,
        status: status,
        id: row.id
      }
      startClose(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.$message({
            type: 'success',
            message: data.msg
          })
          this.searchTmp()
        } else {
          this.$message({
            type: 'error',
            message: data.msg
          })
        }
      })
    },
    // 编辑
    handleEdit (index, row) {
      this.$router.push('/newSetNoticeTemplate')
      this.$store.commit('newNoticeIdFun', row.id)
    },
    // 删除
    handleDelete (index, row) {
      this.deleteSelect([row.id])
    },
    // 新建
    createForm () {
      this.$store.commit('newNoticeIdFun', '')
      this.$router.push('/newSetNoticeTemplate')
    },
    // 默认查询
    searchTmp () {
      this.searchTmpList()
    },
    // 列表查询
    searchTmpList () {
      let params = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
      }
      getListNotice(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          this.tableData = data.data
          this.totalDataLength = data.count
          this.origin = -1
          this.tableData.forEach((item, index) => {// 遍历索引,赋值给data数据
            item.index = index
          })
        }
      })
    },
    // 搜索
    searchTmpContent () {
      this.searchTmpData()
    },
    // 列表搜索
    searchTmpData () {
      let params = {
        pageNumber: this.pageNumber,
        pageSize: this.pageSize,
        searchContent: this.setNoticeTMPName
      }
      getListNotice(params).then(res => {
        let data = res.data
        if (data.retCode === 200) {
          console.log(data)
          this.tableData = data.data
          this.origin = -1
          this.tableData.forEach((item, index) => {// 遍历索引,赋值给data数据
            item.index = index
          })
        }
      })

    },
    handleSelectionChange (val) {
      this.selectAllIdLength = val.length
      this.selectAllId = []
      val.map((value, key, index) => {
        this.selectAllId.push(value.id)
      })
      this.changeLists = this.selectAllId
    },
    deleteBatch () {
      if (this.selectAllIdLength === 0) {
        this.$message({ message: '请选择删除项', type: 'error' })
        return
      }
      this.deleteSelect(this.selectAllId)
    },
    deleteSelect (idList) {
      let params = {
        ids: idList
      }
      this.$confirm('确认要删除吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        customClass: 'messageBox-prompt-delete'
      }).then(() => {
        deleteListMsg(params).then(res => {
          if (res.data.retCode === 200) {
            this.$message({ message: res.data.msg, type: 'success' })
            this.searchTmpList()
          } else {
            this.$message({ message: res.data.msg, type: 'error' })
          }
        })
      })
    },
    // 时间戳的转换
    timestampToTime (timestamp) {
      return common.timestampToTime(timestamp)
    }
  }
}
</script>
<style scoped>
.paging-foot {
  margin-right: 0 !important;
}
.el-pagination-style {
  text-align: right;
}
>>> .el-button--text {
  line-height: 16px;
}
.select-number {
  color: #b50029;
  font-size: 13px;
  padding: 0 5px;
}
</style>
